<script setup>
import { ref, onMounted, watch } from "vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import {
  getFavoritesListApi,
  createFavoriteApi,
  favoriteVideoApi,
} from "@/api/favorites";
import { ElMessage } from "element-plus";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  videoId: {
    type: String,
    default: null,
  },
});

const emit = defineEmits(["close", "collect"]);

const collections = ref([]);
const loading = ref(false);
const errorMsg = ref("");

// 获取用户收藏夹列表
const fetchCollections = async () => {
  if (!props.show) return;

  loading.value = true;
  errorMsg.value = "";

  try {
    const response = await getFavoritesListApi();

    if (response) {
      collections.value = response.map((item) => ({
        ...item,
        selected: false, // 添加选中状态
      }));
    }
  } catch (error) {
    console.error("获取收藏夹列表失败:", error);
    errorMsg.value = "获取收藏夹列表失败，请稍后重试";
  } finally {
    loading.value = false;
  }
};

// 切换收藏夹选择状态
const toggleCollection = (id) => {
  const collection = collections.value.find((c) => c.id === id);
  if (collection) {
    collection.selected = !collection.selected;
  }
};

// 确认收藏
const confirmCollect = async () => {
  if (!props.videoId) {
    console.error("没有指定视频ID");
    return;
  }

  const selectedCollections = collections.value.filter((c) => c.selected);
  if (selectedCollections.length === 0) {
    errorMsg.value = "请选择至少一个收藏夹";
    return;
  }

  loading.value = true;
  errorMsg.value = "";

  try {
    // 将视频添加到所有选中的收藏夹
    const requests = selectedCollections.map((collection) => {
      return favoriteVideoApi(collection.id, props.videoId);
    });

    await Promise.all(requests);

    // 成功后通知父组件并关闭弹窗
    emit("collect", selectedCollections);

    // 重置选择状态
    collections.value.forEach((c) => (c.selected = false));

    emit("close");
  } catch (error) {
    console.error("收藏视频失败:", error);
    if (error.message === "该视频已在收藏夹中") {
      errorMsg.value = "该视频已在收藏夹中";
    } else {
      errorMsg.value = "收藏失败，请稍后重试";
    }
  } finally {
    loading.value = false;
  }
};

// 创建收藏夹相关状态
const showCreateForm = ref(false);
const newCollection = ref({
  name: "",
  description: "",
});
const creatingCollection = ref(false);

// 打开创建收藏夹表单
const openCreateForm = () => {
  showCreateForm.value = true;
  errorMsg.value = "";
};

// 关闭创建收藏夹表单
const closeCreateForm = () => {
  showCreateForm.value = false;
  newCollection.value = { name: "", description: "" };
  errorMsg.value = "";
};

// 创建新收藏夹
const createCollection = async () => {
  if (!newCollection.value.name.trim()) {
    return; // 名称不能为空
  }

  creatingCollection.value = true;

  try {
    const response = await createFavoriteApi({
      name: newCollection.value.name,
      description: newCollection.value.description || "",
    });


    if (response) {
      // 添加新收藏夹到列表中
      collections.value.push({
        ...response,
        selected: true, // 默认选中新创建的收藏夹
      });

      // 提示创建成功
      ElMessage.success("创建收藏夹成功");

      // 关闭创建表单
      closeCreateForm();
    }
  } catch (error) {
    console.error("创建收藏夹失败:", error);
    errorMsg.value = "创建收藏夹失败，请稍后重试";
  } finally {
    creatingCollection.value = false;
  }
};

// 监听弹窗显示状态变化，显示时获取收藏夹列表
watch(
  () => props.show,
  (newValue) => {
    if (newValue) {
      fetchCollections();
    }
  }
);

// 组件挂载时获取收藏夹列表
onMounted(() => {
  if (props.show) {
    fetchCollections();
  }
});
</script>

<template>
  <div class="collection-modal-wrapper" v-if="show" @click.self="emit('close')">
    <div class="collection-modal">
      <div class="modal-header">
        <h3>收藏到</h3>
        <SvgIcon icon-class="close" :size="20" @click="emit('close')" />
      </div>

      <!-- 错误提示 -->
      <div class="error-message" v-if="errorMsg">
        {{ errorMsg }}
      </div>

      <!-- 加载中状态 -->
      <div class="loading-state" v-if="loading">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>

      <!-- 收藏夹列表 -->
      <div class="collections-list" v-else>
        <div v-if="collections.length === 0" class="empty-state">
          <p>暂无收藏夹，请创建一个新收藏夹</p>
        </div>
        <div
          v-else
          v-for="collection in collections"
          :key="collection.id"
          class="collection-item"
          :class="{ selected: collection.selected }"
          @click="toggleCollection(collection.id)"
        >
          <div class="collection-info">
            <div class="collection-name">{{ collection.name }}</div>
            <div class="collection-count">
              {{ collection.video_count || 0 }}个视频
            </div>
          </div>
          <div class="checkbox">
            <SvgIcon
              :icon-class="collection.selected ? 'checked' : 'unchecked'"
              :size="20"
            />
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <div class="create-collection" @click="openCreateForm">
          <SvgIcon icon-class="add" :size="20" />
          <span>创建新收藏夹</span>
        </div>
        <div class="btn-group">
          <button class="cancel-btn" @click="emit('close')">取消</button>
          <button
            class="confirm-btn"
            @click="confirmCollect"
            :disabled="loading"
          >
            确定
          </button>
        </div>
      </div>

      <!-- 创建收藏夹表单弹窗 -->
      <div
        class="create-form-modal"
        v-if="showCreateForm"
        @click.self="closeCreateForm"
      >
        <div class="create-form">
          <div class="form-header">
            <h3>创建新收藏夹</h3>
            <SvgIcon icon-class="close" :size="20" @click="closeCreateForm" />
          </div>

          <!-- 创建表单错误提示 -->
          <div class="error-message" v-if="errorMsg">
            {{ errorMsg }}
          </div>

          <div class="form-content">
            <div class="form-group">
              <label for="collection-name">收藏夹名称</label>
              <input
                type="text"
                id="collection-name"
                v-model="newCollection.name"
                placeholder="请输入收藏夹名称"
                maxlength="20"
              />
              <span class="char-count">{{ newCollection.name.length }}/20</span>
            </div>

            <div class="form-group">
              <label for="collection-description">收藏夹描述</label>
              <textarea
                id="collection-description"
                v-model="newCollection.description"
                placeholder="请输入收藏夹描述（选填）"
                maxlength="50"
              ></textarea>
              <span class="char-count"
                >{{ newCollection.description.length }}/50</span
              >
            </div>
          </div>

          <div class="form-footer">
            <button class="cancel-btn" @click="closeCreateForm">取消</button>
            <button
              class="confirm-btn"
              @click="createCollection"
              :disabled="!newCollection.name.trim() || creatingCollection"
            >
              {{ creatingCollection ? "创建中..." : "创建" }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.collection-modal-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1100; // 修改此值，确保高于VideoPlayModal的z-index
  display: flex;
  align-items: center;
  justify-content: center;

  .collection-modal {
    width: 80%;
    max-width: 350px;
    background-color: white;
    border-radius: 12px;
    overflow: hidden;

    .modal-header {
      padding: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;

      h3 {
        margin: 0;
        font-size: 16px;
        color: #333;
      }
    }

    .collections-list {
      max-height: 300px;
      overflow-y: auto;
      /* 自定义滚动条 */
      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;

        &:hover {
          background: #aaa;
        }
      }

      .collection-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #f5f5f5;
        cursor: pointer;
        transition: background-color 0.2s ease;

        &:hover {
          background-color: #fafafa;
        }

        &.selected {
          background-color: #f0f0f0;
        }

        .collection-info {
          .collection-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
          }

          .collection-count {
            font-size: 12px;
            color: #999;
          }
        }

        .checkbox {
          color: #666;

          &.selected {
            color: #ff4040;
          }
        }
      }
    }

    .create-collection {
      display: flex;
      align-items: center;
      color: #3498db;
      font-size: 14px;
      padding: 12px 16px;
      cursor: pointer;
      border-bottom: 1px solid #eee;

      span {
        margin-left: 8px;
      }

      &:hover {
        background-color: #f5f9fd;
      }
    }

    .modal-footer {
      padding: 12px 16px;
      display: flex;
      justify-content: space-between;

      button {
        padding: 8px 16px;
        border-radius: 4px;
        font-size: 14px;
        margin-left: 12px;
        border: none;
        cursor: pointer;
      }

      .btn-group {
        display: flex;
        align-items: center;

        .cancel-btn {
          background-color: #f5f5f5;
          color: #666;
        }

        .confirm-btn {
          background-color: #3490dc;
          color: white;
        }
      }
    }
  }

  /* 创建收藏夹表单样式 */
  .create-form-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1110; // 从110提高到1110
    display: flex;
    align-items: center;
    justify-content: center;

    .create-form {
      width: 80%;
      max-width: 350px;
      background-color: white;
      border-radius: 12px;
      overflow: hidden;

      .form-header {
        padding: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #eee;

        h3 {
          margin: 0;
          font-size: 16px;
          color: #333;
        }
      }

      .form-content {
        padding: 16px;

        .form-group {
          margin-bottom: 16px;
          position: relative;

          label {
            display: block;
            font-size: 14px;
            color: #333;
            margin-bottom: 8px;
          }

          input,
          textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;

            &:focus {
              outline: none;
              border-color: #3498db;
            }
          }

          textarea {
            resize: none;
            height: 80px;
          }

          .char-count {
            position: absolute;
            right: 5px;
            bottom: 5px;
            font-size: 12px;
            color: #999;
          }
        }
      }

      .form-footer {
        padding: 12px 16px;
        display: flex;
        justify-content: flex-end;
        border-top: 1px solid #eee;

        button {
          padding: 8px 16px;
          border-radius: 4px;
          font-size: 14px;
          margin-left: 12px;
          border: none;
          cursor: pointer;

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }
        }

        .cancel-btn {
          background-color: #f5f5f5;
          color: #666;
        }

        .confirm-btn {
          background-color: #3498db;
          color: white;
        }
      }
    }
  }
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24px 0;

  .loading-spinner {
    width: 24px;
    height: 24px;
    border: 2px solid rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    border-top-color: #3498db;
    animation: spin 1s linear infinite;
    margin-bottom: 8px;
  }

  span {
    color: #666;
    font-size: 14px;
  }
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 0;
  color: #999;
  font-size: 14px;
}

.error-message {
  padding: 8px 16px;
  background-color: #ffebee;
  color: #f44336;
  font-size: 14px;
  text-align: center;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
